package de.fhkoeln.avs.pbfs;

import java.util.HashMap;
import java.util.Iterator;

import com.infinitegraph.ConfigurationException;
import com.infinitegraph.GraphDatabase;
import com.infinitegraph.StorageException;
import com.infinitegraph.Transaction;
import com.infinitegraph.Vertex;

import de.fhkoeln.avs.mockup.RAMPersistentVertex;
import de.fhkoeln.avs.storage.AvsVertex;

public class CacheBuilder {

	public static AvsVertex cacheGraphAndReturnStart(String startTerm) throws StorageException, ConfigurationException {
		//TODO: Wenn Zeit dann refactorn
		HashMap<String, AvsVertex> cached = new HashMap<String, AvsVertex>();
		GraphDatabase graph = DatabaseConnection.getConnection();
		Transaction tx = graph.beginTransaction();
		Iterator<Vertex> verticesOfGraph = graph.getVertices().iterator();
		while (verticesOfGraph.hasNext()) {
			AvsVertex vertex = (AvsVertex) verticesOfGraph.next();
			RAMPersistentVertex cachedVertex = (RAMPersistentVertex) cached.get(vertex.getName());
			if (cachedVertex == null) {
				cachedVertex = new RAMPersistentVertex();
				cachedVertex.setName(vertex.getName());
				cachedVertex.setOwner(vertex.getOwner());
				cached.put(cachedVertex.getName(), cachedVertex);
			}
			for (AvsVertex child : vertex.getChilds()) {
				RAMPersistentVertex childCachedVertex = (RAMPersistentVertex) cached.get(child.getName());
				if (childCachedVertex == null) {
					childCachedVertex = new RAMPersistentVertex();
					childCachedVertex.setName(child.getName());
					childCachedVertex.setOwner(child.getOwner());
					cached.put(childCachedVertex.getName(), childCachedVertex);
				}
				cachedVertex.addChild(childCachedVertex);
			}
		}
		tx.commit();
		return cached.get(startTerm);
	}
}
